
import db
from datetime import datetime, timedelta
from datasource import datasdk
from settings import DEFAULT_CAL_EXCHANGE
from utils.format import d2id, id2d

days_long_everytime = 360

class TradeCalController(object):

    @classmethod
    def get_recent_trade_cal(cls, exchange):
        """get recent cal"""
        start_date = datetime.now()
        end_date = start_date + timedelta(days=30)
        trade_cal = db.TradeCalTB.select().where(
                exchange=exchange,
                cal_date=("between", [d2id(start_date), d2id(end_date)])
            ).order_by("cal_date").all()
        return trade_cal

    @classmethod
    def pull_one_year_trade_cal(cls):
        start_date = datetime.now()-timedelta(days=30)
        end_date = start_date + timedelta(days=days_long_everytime)
        trade_cal_df = datasdk.get_trade_cal(str(d2id(start_date)), str(d2id(end_date)))
        if trade_cal_df.empty:
            raise Exception("取日历为空")
        db.TradeCalTB.rm(cal_date=("between", [d2id(start_date), d2id(end_date)]))
        db.TradeCalTB.add_batch(trade_cal_df.to_dict(orient="records"))
        return {}

    # @staticmethod
    # def next_trade_day(checkdate=None, exchange=DEFAULT_CAL_EXCHANGE):
    #     """获取下一个交易日"""
    #     if not checkdate:
    #         checkdate = d2id(datetime.now())
    #     cal = db.TradeCalTB.find_one(cal_date=checkdate, exchange=exchange)
    #     if cal["is_open"] == 0:
    #         next_cal = db.TradeCalTB.find_one(pretrade_date=cal["pretrade_date"], is_open=1, exchange=exchange)
    #     else:
    #         next_cal = db.TradeCalTB.find_one(pretrade_date=checkdate, is_open=1, exchange=exchange)
    #     return next_cal["cal_date"]

